package jrmob.yonyou.com.commonlib.baseManager;

import android.app.ActivityManager;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;


/**
 * 应用程序Activity管理类：用于Activity管理和应用程序退出
 */
public class AppManager_lib {


	private static Stack<BaseActivityMob_lib> m_activityStack; // activity栈
	private static AppManager_lib m_instance;


	private AppManager_lib() {
	}





	/**
	 * 单一实例
	 * 
	 * @param
	 * @return CAppManager 返回实例
	 */
	public static AppManager_lib getAppManager() {
		if (m_instance == null) {
			m_instance = new AppManager_lib();
		}
		return m_instance;
	}

	/**
	 * 添加Activity到堆栈
	 *
	 *            需要加入的Activity
	 * @return
	 */
	public void addActivity(BaseActivityMob_lib activity) {
		if (m_activityStack == null) {
			m_activityStack = new Stack<BaseActivityMob_lib>();
		}
		m_activityStack.add(activity);
	}

	/**
	 * 获取当前Activity（堆栈中最后一个压入的）
	 * 
	 * @param
	 * @return 返回当前Activity
	 */
	public BaseActivityMob_lib currentActivity() {
		BaseActivityMob_lib activity = m_activityStack.lastElement();
		return activity;
	}

	/**
	 * 结束当前Activity（堆栈中最后一个压入的）
	 * 
	 * @param
	 * @return
	 */
	public void finishActivity() {
		BaseActivityMob_lib activity = m_activityStack.lastElement();
		finishActivity(activity);
	}

	/**
	 * 结束指定的Activity
	 *
	 *            指定结束的Activity
	 * @return
	 */
	public void finishActivity(BaseActivityMob_lib activity) {
		if (activity != null) {
			m_activityStack.remove(activity);
			activity.finish();
			activity = null;
		}
	}

	/**
	 * 结束指定类名的Activity
	 *
	 *            <?> 指定结束的cls
	 * @return
	 */
	public void finishActivity(Class<?> cls) {
		for (BaseActivityMob_lib activity : m_activityStack) {
			if (activity.getClass().equals(cls)) {
				finishActivity(activity);
			}
		}
	}

	/**
	 * 结束所有Activity
	 * 
	 * @param
	 * @return
	 */
	public void finishAllActivity() {
		for (int i = 0, size = m_activityStack.size(); i < size; i++) {
			if (null != m_activityStack.get(i)) {
				m_activityStack.get(i).finish();
			}
		}
		m_activityStack.clear();
	}

	/**
	 * 退出应用程序
	 * 
	 * @param
	 *
	 * @return
	 */
	public void AppExit(Context context) {
		try {
			finishAllActivity();
			ActivityManager activityMgr = (ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE);
			activityMgr.restartPackage(context.getPackageName());
			System.exit(0);
		} catch (Exception e) {
		}
	}
}
